package io.github.wx.service;

import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import io.github.wx.common.easyui.DataGrid;
import io.github.wx.dao.model.BizNews;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * Created by jie on 2017/4/19
 * BizNewsService.
 */
public class BizNewsService {
    private static final String REDIS_NEWS_KEY = "newsIds";
    private static final int PAGESIZE = 50;

    public void spiderData() {
        try {
            getData(1492655361000L);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getData(long DateLong) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pageSize", PAGESIZE);
        params.put("lastCursor", DateLong);
        LogKit.info("lastCursor:" + DateLong);
        String url = "https://api.readhub.me/news";
        String reuslt = HttpUtil.get(url, params);
        JSONObject jsonObject = JSONUtil.parseObj(reuslt);
        List<JSONObject> list = (List<JSONObject>) jsonObject.get("data");
        for (JSONObject newsObject : list) {
            Integer fieldId = newsObject.getInt("id");
            boolean haveId = Redis.use().hexists(REDIS_NEWS_KEY, fieldId);

            if (!haveId) {
                BizNews news = newsObject.toBean(BizNews.class);
                try {
                    LogKit.info("新闻:" + news.getTitle());
                    news.save();
                } catch (Exception e) {
                    LogKit.error("新闻:" + news.getTitle());
                }
                Redis.use().hset(REDIS_NEWS_KEY, fieldId, news.getPublishDate());
            }
        }

        if (list != null && list.size() > 1) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            df.setTimeZone(TimeZone.getTimeZone("UTC"));
            JSONObject jsonObj = list.get(list.size() - 1);
            long time = df.parse(jsonObj.getStr("publishDate")).getTime();
            getData(time);
        }

    }

    public DataGrid getNewsPage(Integer page, Integer rows) {
        String select = "SELECT biz_news.id, biz_news.site_name, biz_news.author_name, biz_news.url, biz_news.title , biz_news.summary, biz_news.publish_date, biz_news.create_time ";
        String sqlExcepteSelect = "FROM biz_news ORDER BY biz_news.create_time DESC ";
        Page<BizNews> bizNewsPage = BizNews.dao.paginate(page,rows,select,sqlExcepteSelect);
        return new DataGrid(bizNewsPage);
    }
}
